package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/6/30 15:47
 */

@Component
public class RedisCacheInterceptor implements HandlerInterceptor {

    @Value("${tanhua.cache.enable}")
    private Boolean enableCache;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    //前置
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //首相判断全局缓存是否开启：
        if (!enableCache) {
            //如果没有开启，则放行：
            return true;
        }

        //判断handle是否是handleMethod:
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断请求是否是Get请求：
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }

        //判断是否添加cache注解：
        if (!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return true;
        }

        //设置redisKey:
        String redisKey = createRedisKey(request);
        System.out.println(redisKey);

        String cacheData = redisTemplate.opsForValue().get(redisKey);

        if (ObjectUtils.isEmpty(cacheData)) {
            //如果数据为空，则
            return true;
        }
        //如果缓存命中：直接返回：
        // 将data数据进行响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }

    public static  String createRedisKey(HttpServletRequest request) throws JsonProcessingException {

//        生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
        String param = OBJECT_MAPPER.writeValueAsString(request.getParameterMap());
        String url = request.getRequestURI();
        String token = request.getHeader("Authorization");
        String data = url + param + token;
        return "SERVER_CACHE_DATA_" + DigestUtils.md2Hex(data);
    }
}
